package com.demo.common.aop;

import com.demo.common.base.ResultModel;
import com.demo.common.constants.ConstantsCommon;
import com.demo.common.exception.BusinessException;
import com.demo.model.UserInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Description: LoginAopAnnotation
 * @Author: ChenXueLi
 * @Date: 2018-10-05 17:56
 */
@Aspect
@Component
public class LoginAspect {

    @Pointcut("@annotation(com.demo.common.aop.LoginAop)")
    public void loginAop() {
    }

    @Before("loginAop() && @annotation(data)")
    public void doBefore(JoinPoint point, LoginAop data) throws Throwable {
        // 获取request以及seesion
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        // 获得当前用户
        UserInfo loginUser = (UserInfo) session.getAttribute(ConstantsCommon.LOGIN_INFO);
        if (loginUser == null) {
            throw new BusinessException(-9, "登陆超时，请重新登陆");
        }

        ResultModel resultModel = new ResultModel();
        if (point.getArgs() != null) {
            for (Object obj : point.getArgs()) {
                if (obj != null && obj.getClass() == ResultModel.class) {
                    resultModel = (ResultModel) obj;
                    break;
                }
            }
        }
        resultModel.setUserInfo(loginUser);

    }

}
